package org.opens.lambda.collector;

import org.junit.Test;
import org.opens.lambda.UserEntity;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToArray {

    @Test
    public void test1() {
        List<UserEntity> list = UserEntity.getList(10);
        Integer[] ageArr = list.stream().map(UserEntity::getAge).toArray(Integer[]::new);
        for (Integer age : ageArr) {
            System.out.println(age);
        }

        String[] names = list.stream().map(UserEntity::getName).toArray(String[]::new);
        for (String name : names) {
            System.out.println(name);
        }

        // 注意：此处的toArray函数的x表示对应数组的元素个数；
        Integer[] ageArr2 = list.stream().map(UserEntity::getAge).toArray(x -> {
            System.out.println(">>> " + x);
            return new Integer[x];
        });
        for (Integer age : ageArr2) {
            System.out.println(age);
        }
    }

    @Test
    public void test2() {
        Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        List<UserEntity> collect = Stream.of(arr).map(x -> {
            UserEntity randomUser = UserEntity.getRandomUser();
            randomUser.setAge(x);
            return randomUser;
        }).collect(Collectors.toList());
        System.out.println(collect);
    }

}
